package com.yunsc.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.system.dao.YunscStoreUserRoleDao;
import com.yunsc.system.entity.YunscStoreUserRoleEntity;
import com.yunsc.system.service.YunscStoreUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service("yunscStoreUserRoleService")
public class YunscStoreUserRoleServiceImpl extends ServiceImpl<YunscStoreUserRoleDao, YunscStoreUserRoleEntity> implements YunscStoreUserRoleService {


    @Override
    @Transactional
    public void editUserRole(Integer storeUserId, List<Integer> roles, Integer storeId) {
        List<YunscStoreUserRoleEntity> storeUserRoleList = this.list(new LambdaQueryWrapper<YunscStoreUserRoleEntity>()
                .eq(YunscStoreUserRoleEntity::getStoreUserId, storeUserId));
        // 根据查询是否存在记录，存在则删除数据库记录和删除对应roles
        // 存储待删除的分类ID
        List<Integer> toDeleteIds = new ArrayList<>();

        for (YunscStoreUserRoleEntity role : storeUserRoleList) {
            if (!roles.contains(role.getId())) {
                // 如果不在新分类中，标记为待删除
                toDeleteIds.add(role.getId());
            } else {
                roles.remove(role.getId());
            }
        }
        // 删除不再关联的分类
        this.removeByIds(toDeleteIds);

        // 添加新的商品与分类关系
        // 新增对应关系
        // YunscStoreUserRoleService storeUserRoleService = SpringUtil.getBean(YunscStoreUserRoleService.class);
        // storeUserRoleService.addUserRole(storeUserId, roles, storeId);
        this.addUserRole(storeUserId, roles, storeId);
    }

    @Override
    @Transactional
    public void addUserRole(Integer storeUserId, List<Integer> roles, Integer storeId) {
        // 添加新的商品与分类关系
        // 新增对应关系
        List<YunscStoreUserRoleEntity> userRoleEntityList = roles.stream().map(roleId -> {
            YunscStoreUserRoleEntity userRole = new YunscStoreUserRoleEntity();
            userRole.setRoleId(roleId);
            userRole.setStoreId(storeId);
            userRole.setStoreUserId(storeUserId);
            return userRole;
        }).collect(Collectors.toList());
        this.saveBatch(userRoleEntityList);
    }


}